package com.example.gyj.service;

import com.example.gyj.entity.OrderInfo;
import com.example.gyj.entity.SeckillOrder;
import com.example.gyj.entity.User;
import com.example.gyj.redis.SeckillKey;
import com.example.gyj.util.Md5Util;
import com.example.gyj.util.UUIDUtil;
import com.example.gyj.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;

/**
 *
 * @author Gao
 * @date 2018/10/21
 */
@Service
public class SeckillService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisService redisService;

   /* @Transactional
    public OrderInfo seckill(User user, GoodsVo goods) {
        //减库存 下订单 写入秒杀订单
        goodsService.reduceStock(goods);
        //order_info和s_order
        return orderService.createOrder(user, goods);
    }*/

    /**
     * 写入秒杀订单，一个用户一个商品订单
     *
     * @param user
     * @param goods
     */
    @Transactional
    public OrderInfo seckill(User user, GoodsVo goods) {
        //减库存
        boolean success = goodsService.reduceStock(goods);
        if (success) {
            //下订单，写入秒杀订单 操作 order_info和s_order两张表
            return orderService.createOrder(user, goods);
        } else {
            redisService.set(SeckillKey.isGoodsOver, "" + goods.getId(), true);
            return null;
        }
    }


    /**
     * 获取秒杀结果
     * @param userId
     * @param goodsId
     */
    public long getSeckillResult(Long userId, long goodsId) {

        SeckillOrder order = orderService.getSeckillOrderByUserIdGoodsId(userId, goodsId);
        //秒杀成功
        if (order != null) {
            return order.getOrderId();
        } else {
            //判断秒杀是否结束的key是否存在
            boolean isOver = redisService.exists(SeckillKey.isGoodsOver, "" + goodsId);
            if (isOver) {
                return -1;
            } else {
                return 0;
            }
        }
    }

    /**
     * 生成图形验证码
     *
     * @param user
     * @param goodsId
     */
    public BufferedImage createVerifyCode(User user, long goodsId) {
        if (user == null || goodsId <= 0) {
            return null;
        }
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }

        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码的计算结果存到redis中
        int rnd = calc(verifyCode);
        boolean set = redisService.set(SeckillKey.getSeckillVerifyCode, user.getId() + "_" + goodsId, rnd);
        System.out.println("设置验证码是否成功：" + set);
        //输出图片
        return image;
    }

    private static char[] ops = new char[]{'+', '-', '*'};

    /**
     * 生成一个随机的code
     * @param rdm
     */
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = "" + num1 + op1 + num2 + op2 + num3;
        return exp;
    }

    /**
     * 利用 js 引擎计算结果
     */
    private int calc(String exp) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        try {
            return (Integer) engine.eval(exp);
        } catch (ScriptException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 校验验证码
     * @param user
     * @param goodsId
     * @param verifyCode
     */
    public boolean checkVerifyCode(User user, long goodsId, int verifyCode) {
        if (user == null || goodsId <= 0) {
            return false;
        }
        Integer codeId = redisService.get(SeckillKey.getSeckillVerifyCode,
                user.getId() + "_" + goodsId, Integer.class);
        //验证传过来的验证码和redis中的是否相等
        if (codeId == null || codeId - verifyCode != 0) {
            return false;
        }
        //从redis中删除验证码，否则下次还会继续用
        redisService.delete(SeckillKey.getSeckillVerifyCode, user.getId() + "_" + goodsId);

        return true;
    }

    /**
     * 验证秒杀路径
     * @param user
     * @param goodsId
     * @return
     */
    public String createSeckillPath(User user, long goodsId) {
        if (user == null || goodsId <= 0) {
            return null;
        }
        String str = Md5Util.md5(UUIDUtil.uuid() + "123456");
        redisService.set(SeckillKey.getSeckillPath, "" + user.getId() + "_" + goodsId, str);
        return str;
    }

    /**
     * 秒杀路径
     * @param user
     * @param goodsId
     * @param path
     * @return
     */
    public boolean checkPath(User user, long goodsId, String path) {
        if (user == null || path == null) {
            return false;
        }
        String pathOld = redisService.get(SeckillKey.getSeckillPath, "" + user.getId() + "_" + goodsId, String.class);
        return path.equals(pathOld);
    }

    public void reset(List<GoodsVo> goodsList) {
        goodsService.resetStock(goodsList);
        orderService.deleteOrders();
    }
}
